package org.dromara.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.study.domain.entity.Department;
import org.dromara.study.domain.vo.DepartmentTreeVo;
import org.dromara.study.mapper.DepartmentMapper;
import org.dromara.study.service.DepartmentService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<DepartmentTreeVo> getTree() {
        List<Department> departments = departmentMapper.selectList(new LambdaQueryWrapper<>());
        return formatTree(departments);
    }

    private List<DepartmentTreeVo> formatTree(@NotNull List<Department> departments) {
        List<DepartmentTreeVo> departmentTreeVoList = new ArrayList<>();
        // 将所有部门转换为 DepartmentTreeVo
        List<DepartmentTreeVo> allNodes = departments.stream()
            .map(DepartmentTreeVo::new) // 假设 DepartmentTreeVo 有对应的构造函数或转换方法
            .toList();

        // 找到所有根节点（parentId 为 null）
        for (DepartmentTreeVo node : allNodes) {
            if (node.getParentId() == null) {
                departmentTreeVoList.add(node);
            }
        }

        // 递归设置子节点
        for (DepartmentTreeVo node : departmentTreeVoList) {
            setChildren(node, allNodes);
        }

        return departmentTreeVoList;
    }

    private void setChildren(DepartmentTreeVo parent, @NotNull List<DepartmentTreeVo> allNodes) {
        List<DepartmentTreeVo> children = new ArrayList<>();
        for (DepartmentTreeVo node : allNodes) {
            if (node.getParentId() != null && node.getParentId().equals(parent.getId())) {
                children.add(node);
                setChildren(node, allNodes); // 递归设置子节点
            }
        }
        parent.setChildren(children); // 假设 DepartmentTreeVo 有 setChildren 方法
    }
}
